package controller

import (
	"net/http"
	"net/url"
	"sale-admin/config"
	"sale-admin/config/mysql"
	"sale-admin/internal/app/web/service"
	"sale-admin/internal/dao"
	"sale-admin/internal/define"
	"sale-admin/internal/models"
	"sale-admin/internal/pkg"

	"192.168.1.75/go-pkg/errorx"
	"192.168.1.75/go-pkg/response"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
)

type H5Page struct{}

// 获取位置信息
func (H5Page) GetLocationInfo(c *gin.Context) {
	salesID := c.Query("sales_id")
	db := mysql.NewDB()
	data, err := service.OrderPoints{}.GetRobotLocationInfo(c.Request.Context(), db, salesID)
	response.JSON(c, data, err)
}

//  1. 用户授权。获得token
//  2. 通过code换取网页授权access_token
//  3. 刷新access_token
//  4. 拉取用户信息(scope = snsapi_userinfo)
//  5. 检验授权凭证(access_token)是否有效
//  6. 调用频率限制:
//     -----------------------------------------------------------
//     |	通过 code 换取 access_token		| 		5 万/分钟
//     |	获取用户基本信息				 | 	 	 5 万/分钟
//     |	刷新 access_token				| 		10 万/分钟
//     -----------------------------------------------------------
func (H5Page) GetWechatInfo(c *gin.Context) {
	var URL url.URL
	query := URL.Query()
	query.Add("sales_id", c.Query("sales_id")) // 机器码
	query.Add("order_id", c.Query("order_id")) // 订单号

	// 接收Ticket
	Ticket := c.Query("Ticket") // 猫酷返回的ticket凭证

	code := c.Query("code")
	// 1.获取积分类型
	db := mysql.NewDB()
	RobotLocationInfo, err1 := service.OrderPoints{}.GetRobotLocationInfo(c.Request.Context(), db, c.Query("sales_id"))
	if err1 != nil || RobotLocationInfo.PointsId == "" {
		response.JSON(c, nil, errorx.New("获取积分类型错误", -1))
	}
	if _, ok := define.PointsType[RobotLocationInfo.PointsId]; !ok {
		response.JSON(c, nil, errorx.New("获取积分类型错误", -1))
	}
	if code != "" {
		accessToken, openid := pkg.Wechat{}.GetAccessToken(c.Request.Context(), code)
		UserInfo := pkg.Wechat{}.GetUserInfo(c.Request.Context(), accessToken, openid)
		if UserInfo.Openid == "" {
			response.JSON(c, nil, errorx.New("获取用户信息失败", -1)) // 40003
		} else {
			// 2.重定向跳转 ，通过回调地址拿到Ticket信息 -- // 获取猫酷的ticket --- 通过Aouth重定向授权获取
			if RobotLocationInfo.PointsId == "3" && Ticket == "" {

				// callbackurl := url.QueryEscape(config.Config.BaseUrl + "/public/h5-page/get-wechat-info?" + query.Encode())

				callbackurl := url.QueryEscape(config.Config.BaseUrl + "/public/h5-page/get-wechat-info?code=" + code + "&sales_id=" + c.Query("sales_id") + "&order_id=" + c.Query("order_id"))

				getTicketUrl := "https://m.mallcoo.cn/a/open/User/V2/OAuth/BaseInfo?AppID=" + config.Config.MallcooPoints.APPID + "&PublicKey=" + config.Config.MallcooPoints.PublicKey + "&CallbackUrl=" + callbackurl
				// 跳转
				c.Redirect(http.StatusSeeOther, getTicketUrl)
				return
			}

			WechatUserInfo, _ := dao.WechatUser{}.Detail(c.Request.Context(), db, "", UserInfo.Openid)
			if WechatUserInfo == nil || WechatUserInfo.OpenID == "" { //新增
				// 写入微信用户的基础信息
				dao.WechatUser{}.Create(c.Request.Context(), db, UserInfo.Nickname, UserInfo.Headimgurl, UserInfo.Openid)
			}
			// 3.微信基础信息写入成功后，再更新猫酷Ticket
			if RobotLocationInfo.PointsId == "3" && Ticket != "" {
				db.Model(&models.MaWechatUser{}).
					Where("open_id = ?", UserInfo.Openid).
					UpdateColumn("mallcoo_ticket", Ticket)
			}

			query.Add("openid", UserInfo.Openid) // 用户openid
			H5PageURL := config.Config.BaseUrl + "/h5-page/points/index.html#/cart?" + query.Encode()
			c.Redirect(http.StatusSeeOther, H5PageURL)
		}
	} else {
		redirectUri := c.Request.URL
		//默认静默授权
		AuthorizeURL := pkg.Wechat{}.GetAuthorizeURL(config.Config.BaseUrl+redirectUri.Path+"?"+query.Encode(), "", "")
		c.Redirect(http.StatusSeeOther, AuthorizeURL)
	}
}

// 获取正弘城用户信息
func (H5Page) GetMemberInfo(c *gin.Context) {
	openid := c.Query("openid")
	salesID := c.Query("sales_id")

	data, err := service.OrderPoints{}.MemberInfo(c.Request.Context(), salesID, openid)

	response.JSON(c, data, err)
}

// 2.用户注册
func (H5Page) MemberRegist(c *gin.Context) {
	var params struct {
		SalesID    string `json:"sales_id"`   // 机器 【必填】
		Phone      string `json:"phone"`      // 电话 【必填】
		Code       string `json:"code"`       // 短信验证码
		Name       string `json:"name"`       // 姓名
		Gender     int    `json:"gender"`     // 性别 (0未知 1 男 2 女)
		IdCard     string `json:"idCard"`     // 身份证号码
		Birthday   string `json:"birthday"`   // 生日 (2000-01-01)
		Address    string `json:"address"`    // 地址
		ProvinceId string `json:"provinceId"` // 省份id
		CityId     string `json:"cityId"`     // 城市id
		AreaId     string `json:"areaId"`     // 市县id
		Openid     string `json:"openid"`     // 微信openid
		HeadImg    string `json:"headImg"`    // 会员头像地址
	}
	c.ShouldBindBodyWith(&params, binding.JSON)

	db := mysql.NewDB()
	err := service.OrderPoints{}.MemberRegist(c.Request.Context(), db, params.SalesID, params.Openid, params.Phone, params.Code, params.Name, params.Gender, params.Birthday, params.IdCard, params.HeadImg, params.ProvinceId, params.CityId, params.AreaId, params.Address)
	response.JSON(c, nil, err)
}

// 获取购物车信息
func (H5Page) GetCartGoods(c *gin.Context) {
	var params struct {
		OrderID string `json:"order_id"` // 订单号
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	totalAmount, data, err := service.OrderPoints{}.GetCartGoods(c.Request.Context(), params.OrderID)
	response.JSON(c, gin.H{
		"total_amount": totalAmount,
		"list":         data,
	}, err)
}

// WechatJspay 调取微信的jsapi支付，返回相关参数供前端使用
func (H5Page) WechatJspay(c *gin.Context) {
	var params struct {
		OrderID string  `json:"order_id"` // 订单号
		Openid  string  `json:"openid"`   // openid
		Points  float64 `json:"points"`   // 积分
	}
	c.ShouldBindBodyWith(&params, binding.JSON)
	data, err := service.OrderPoints{}.WechatJspay(c.Request.Context(), params.OrderID, params.Openid, params.Points, 0)
	response.JSON(c, data, err)
}
